package com.adee.secure;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 对称加密：AES
 * 为什么原来的DES会被取代呢，原因就在于其使用56位密钥，比较容易被破解。而AES可以使用128、192、
 * 和256位密钥，并且用128位分组加密和解密数据，相对来说安全很多。
 *
 */
public class Test004_AES {
    static final String AES = "AES";

    public static void main(String[] args) {
        String content = "有一个美丽滴传说，精美的石头会唱歌";
        String password = "123";
        System.out.println("加密之前：" + content);

        // 加密
        String base64Str = encrypt(content.getBytes(StandardCharsets.UTF_8), password);
        System.out.println("加密后的内容：" + base64Str);

        // 解密
        byte[] decrypt = decrypt(base64Str, password);
        System.out.println("解密后的内容：" + new String(decrypt, StandardCharsets.UTF_8));
    }

    // 加密，得到base64串
    public static String encrypt(byte[] content, String password) {
        Key secretKey = getKey(password);
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] result = cipher.doFinal(content);
            return Base64.getEncoder().encodeToString(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 解密
    public static byte[] decrypt(String base64Str, String password) {
        Key secretKey = getKey(password);
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] bytes = Base64.getDecoder().decode(base64Str);
            byte[] result = cipher.doFinal(bytes);
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Key getKey(String keySeed) {
        if (keySeed == null) {
            keySeed = System.getenv("AES_SYS_KEY");
        }
        if (keySeed == null) {
            keySeed = System.getProperty("AES_SYS_KEY");
        }
        if (keySeed == null || keySeed.trim().length() == 0) {
            keySeed = "abcd1234!@#$";// 默认种子
        }
        try {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(keySeed.getBytes());
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            generator.init(secureRandom);
            return generator.generateKey();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
